from typing import List


#  第一种方法超时了
class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        media = len(nums) // 2
        left, right = 0, len(nums)

        while left != right:
            if nums[media] == target:
                break
            elif nums[media] > target:
                right = media
            else:
                left = media

        media_left = media
        media_right = media
        left_targart = 0
        right_target = 0
        while nums[media_left] == target:
            media_left -= 1
            if nums[media_left] != target:
                left_targart = (media_left + 1)
                break

        while nums[media_right] == target:
            media_right += 1
            if nums[media_right] != target:
                right_target = (media_right - 1)
                break
        return [left_targart, right_target]

# 改进改进
    def binery_search(self,left,right,nums:List[int],target) -> int:

        while left!=right:
            media = (left + right) // 2
            if nums[media] >target:
                 right = media-1
            elif nums[media] < left :
                 left = media+1
            elif nums[media-1] != target and nums[media]==target:
                return media

    def searchRange1(self, nums: List[int], target: int) -> List[int]:
        leftIdx = self.binarySearch(nums, target, True)
        rightIdx = self.binarySearch(nums, target, False) - 1
        if (leftIdx <= rightIdx and rightIdx < len(nums) and nums[leftIdx] == target and nums[rightIdx] == target):
              return [leftIdx, rightIdx]

        return [-1, -1]



    def binarySearch(self,nums: List[int], target: int, lower: bool) :
        left = 0
        right = len(nums) - 1
        ans = len(nums)
        while (left <= right) :
            mid = (left + right) // 2
            if (nums[mid] > target or (lower and nums[mid] >= target)) :
                right = mid - 1
                ans = mid
            else :
                left = mid + 1


        return ans



# 写一个二分法


if __name__ == '__main__':

    nums = [5, 7, 7, 8, 8, 10]
    target = 8
    solution = Solution()
    val = solution.searchRange(nums, 8)
    val1 = solution.searchRange1(nums,8)

    print(val)
    print(val1)
